package cn.campus.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by linyanbin on 2018/10/7.
 */
public class CookieUtil {

    private CookieUtil(){}

    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        addCookie(response, name, value, null, maxAge);
    }

    public static void addCookie(HttpServletResponse response, String name, String value) {
        addCookie(response, name, value, null, -1);
    }

    public static void addCookie(HttpServletResponse response, String name) {
        addCookie(response, name, null, null, 0);
    }

    /**
     * 添加Cookie
     * @param response
     * @param name
     * @param value
     * @param domain    域
     * @param maxAge    存活时间
     */
    public static void addCookie(HttpServletResponse response, String name, String value, String domain, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        if (domain != null) {
            cookie.setDomain(domain);
        }
        response.addCookie(cookie);
    }

    /**
     * 删除Cookie
     * @param request
     * @param response
     * @param name
     */
    public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        Cookie cookie = getCookie(request, name);
        if (cookie != null) {
            addCookie(response, name);
        }
    }

    /**
     * 获取Cookie
     * @param request
     * @param name
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }
}
